import React, { Component } from 'react';
import { Table, Input, Button, Popconfirm, Form,Select, Modal,  Divider,Row,Col} from 'antd';
import Content from "../../components/Content/Content";
import moment from "moment";

const EditableContext = React.createContext();
const { Option } = Select;
const InputGroup = Input.Group;
const { TextArea } = Input;
const { Item } = Form;
const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
    visible_yiruku: false,
    visible_detail: false
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title}不可为空！`,
            },
          ],
          initialValue: record[dataIndex],
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        fixed: 'left',
        width:120,
      },
      {
        title: '筛选菌株编号',
        dataIndex: 'sxjj_id',
        
        editable: true,
        fixed: 'left',
        width:200,
      },
      {
        title: '筛选菌株保藏方式',
        dataIndex: 'jzbc_type',
        render: (text, record) => (
          <Select defaultValue={text}
          //mode="tags"
          style={{ width: "100%" }}
          onChange={value => this.setState({jzbc_type : value}) }
          tokenSeparators={[',']}
          showArrow={true}
        >
          <Option value="YD">液氮超低温冻结法</Option>
          <Option value="FB">－80摄氏度冰箱冻结法</Option>
          <Option value="ZK">真空冷冻干燥法</Option>
          <Option value="KW">矿物油法</Option>
          <Option value="YZ">定期移植法</Option>
          <Option value="QT">其他</Option>
        </Select>
              )
      },
      {
        title: '批号',
        editable: true,
        dataIndex: 'change_ph',
      },
      {
        title: '操作人',
        editable: true,
        dataIndex: 'operator',
      },
      {
        title: '操作时间',
        editable: true,
        dataIndex: 'operation_time',
      },
      {
        title: '入库人',
        editable: true,
        dataIndex: 'worker',
      },
      {
        title: '入库时间',
        editable: true,
        dataIndex: 'in_time',
      },
      {
        title: '入库数量',
        editable: true,
        dataIndex: 'in_number',
      },
      {
        title: '存放位置',
        editable: true,
        dataIndex: 'store_place',
      },
      {
        title: '备注',
        editable: true,
        dataIndex: 'remark',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        width:200,
        render: (text, record) => (
          <span>
            <Button type="dashed" onClick={() => this.showViewModal(record)}>
              查看
            </Button>
            <Divider type="vertical" />
            <Popconfirm title="确认删除吗?" onConfirm={() => this.handleDelete(record.id)}>
              <Button type="dashed" >删除</Button>
            </Popconfirm>
          </span>
        )
      },
    ];
    this.columns_yiruku = [
      {
        title: 'ID',
        dataIndex: 'id',
        fixed: 'left',
        width:120,
      },
      {
        title: '筛选菌株编号',
        dataIndex: 'sxjj_id',

        fixed: 'left',
        width:200,
      },
      {
        title: '筛选菌株保藏方式',
        dataIndex: 'jzbc_type',
        render: (text, record) => (
          <Select defaultValue={text}
         // mode="tags"
          style={{ width: "100%" }}
          disabled={true}
          showArrow={true}
        >
          <Option value="XY">需氧</Option>
          <Option value="YY">厌氧</Option>
          <Option value="BH">饱和</Option>
        </Select>
              )
      },
      {
        title: '批号',
        dataIndex: 'change_ph',
      },
      {
        title: '操作人',
        dataIndex: 'operator',
      },
      {
        title: '操作时间',
        dataIndex: 'operation_time',
      },
      {
        title: '入库人',
        dataIndex: 'worker',
      },
      {
        title: '入库时间',
        dataIndex: 'in_time',
      },
      {
        title: '入库数量',
        dataIndex: 'in_number',
      },
      {
        title: '存放位置',
        dataIndex: 'store_place',
      },
      {
        title: '备注',
        dataIndex: 'remark',
      },
     
    ];
    this.state = {
      dataSource: [],
      dataSource_yiruku: [],

      jzbc_type: '',

      count: 0,
      count_yiruku: 0,
      newData: {},
      viewData: {},
      loading: false,
      keyword: ''
    };
  }

  handleDelete = id => {
    const dataSource = [...this.state.dataSource];
    
    // 如果是新数据尚未保存，那么可以直接删除
    if( this.state.newData.id != null ) {
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      return;
    }

    const url = global.api.screeningLibraryIn + id + '/';
    return global.deletedata.del(url, {})
    .then(res => {  
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      Modal.success({
        content: '删除成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '删除出错!',
      });
    }) 
  };

  start = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
  };

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const initVal = count + 1;

    if( this.state.newData.id != null ) {
      Modal.error({
        content: '数据尚未保存！',
      });
      return;
    }
    const newData = {
      id: initVal,
      sxjj_id: initVal,
      jzbc_id : initVal,
      jzbc_type  : '',
      change_ph  : initVal,

      operator  : initVal,
      operation_time  : moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
      worker  : initVal,

      in_time: moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
      in_number : initVal,
      store_place : initVal,
      remark: initVal
    };

    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
      newData: newData
    });
  };

  loadData = (current = 1) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    const url = global.api.screeningLibraryIn;
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search: this.state.keyword})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count, newData: {}})
    })
    .catch(err => {
      Modal.error({
        content: '数据加载失败！'
      })
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  // 显示已入库
  showModal = () => {
    // 先调用接口获取数据，成功后显示Modal
    const url = global.api.screeningLibraryIn222;
    return global.getdata.get(url, {page_index: 1, page_size: this.state.pageSize})
    .then(res => {
      this.setState({visible_yiruku: true, dataSource_yiruku: res.results, count_yiruku: res.count})
    })
    .catch(err => {
      Modal.error({
        content: '数据获取失败！'
      })
    })
  };

  handleOkYiruku = e => {
    console.log(e);
    this.setState({
      visible_yiruku: false,
    });
  };

  handleCancelYiruku = e => {
    console.log(e);
    this.setState({
      visible_yiruku: false,
    });
  };

  showViewModal = (record) => {
    this.setState({
      visible_detail: true,
      viewData: record
    });
  };

  handleOkDetail = e => {
    console.log(e);
    this.setState({
      visible_detail: false,
    });
  };

  handleCancelDetail = e => {
    console.log(e);
    this.setState({
      visible_detail: false,
    });
  };

  handleSave = (row, showAlert) => {
   
    let dataSource = [...this.state.dataSource];
    let record = null;
    if( row.id != null ) {
      record = row;
    } else {
      record = dataSource[dataSource.length - 1];
    }
    record.jzbc_type = this.state.jzbc_type;

    const url = global.api.screeningLibraryIn;
    return global.network.post(url, record)
    .then(res => {  
      this.loadData(1);
      this.setState({newData:{}});
      if( showAlert ) {
        Modal.success({
          content: '保存成功!',
        });
      }
    })
    .catch(err => {
      if( showAlert ) {
        Modal.error({
          content: '保存出错，请检查传入的参数是否已经填写！',
        });
      }
    }) 

  };

  // 导出入库单
  doOutput = () => {
    let selectedRowKeys = this.state.selectedRowKeys;
    if(selectedRowKeys) {
      let ids = [];

      for( let x of selectedRowKeys ) {
        let record = this.state.dataSource[x];
        ids.push( record );
      }

      const url = global.api.screeningLibraryOutput;
      return global.download.down(url, ids)
      .then(res => {

        // let blob = new Blob(['\uFEFF' + res.data], { type: 'application/vnd.ms-excel;charset=UTF-8' })
        let blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=UTF-8' })
        let url = window.URL.createObjectURL(blob)
        console.info(url);

        window.open(url, "_blank")
      })
      .catch(err => {
        Modal.error({
          content: '调用接口出错！',
        });
      }) 

    }   
  }

  // 入库
  doRuku = () => {
     let selectedRowKeys = this.state.selectedRowKeys;
     if(selectedRowKeys) {
       for( let x of selectedRowKeys ) {
         let record = this.state.dataSource[x];
         record.chuli_tag = 'yjs';

         const url = global.api.huijiaoinfo + record.id + '/';
         return global.updatedata.put(url, record)
         .then(res => {  
     
           const newData = [...this.state.dataSource];
           const index = newData.findIndex(item => item.id === record.id);
           const item = newData[index];
           newData.splice(index, 1, {
             ...item,
             ...record,
           });
           this.setState({ dataSource: newData });
     
           Modal.success({
             content: '入库成功!',
           });
         })
         .catch(err => {           
           Modal.error({
             content: '入库出错!',
           });
         }) 

       }
     }
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 }
      }
    };
    const { dataSource, dataSource_yiruku, loading, selectedRowKeys } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    const columns_yiruku= this.columns_yiruku.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Content>
          <div className="filtrate">
          <p style={{marginLeft:'100px'}}>
          <span className="span">
         <Input placeholder="输入查询内容" style={{ width: 250 }}  onChange={value => this.setState({keyword: value})} />
          </span>
          <span className="span" >
            <Button loading={this.state.loading} type="primary" style={{ width: 80 }} onClick={this.loadData.bind('click', 1)}>
              查询
            </Button>
          </span>
          </p>
        </div>
        <div style={{marginTop: '50px',marginLeft: 16}}>
        <Button  type="primary" onClick={this.doRuku} >
          入库
        </Button>
        <Button  type="primary" onClick={this.showModal} style={{marginLeft: 16}}>
          已入库
        </Button>
        <Button  type="primary" onClick={this.doOutput} style={{marginLeft: 16}}>
          导出入库单
        </Button>
         </div>

        <Modal
          title="Basic Modal"
          visible={this.state.visible_yiruku}
          onOk={this.handleOkYiruku}
          onCancel={this.handleCancelYiruku}
        >
        <Button type="primary" style={{ marginLeft: 16, display: 'none' }}>
          保存
        </Button>
        <Table
          rowSelection={rowSelection}
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource_yiruku}
          columns={columns_yiruku}
          scroll={{ x: 3500}}
        />
        </Modal>
        <Modal
          title="Basic Modal"
          visible={this.state.visible_detail}
          onOk={this.handleOkDetail}
          onCancel={this.handleCancelDetail}
        >
        <Form {...formItemLayout} onSubmit={this.onSubmit} colon={false}>
        <div style={{display:'flex'}}>
          <span style={{flex:'1'}}>
            <Item label="筛选菌株编号"><Input value={this.state.viewData.sxjj_id } /></Item>
            <Item label="菌株保藏编号"><Input value={this.state.viewData.jzbc_id } /></Item>
            <Item label="菌株保藏方式"><Input value={this.state.viewData.jzbc_type } /></Item>
            <Item label="入库保藏的批号"><Input value={this.state.viewData.change_ph } /></Item>
            <Item label="操作人"><Input value={this.state.viewData.operator } /></Item>
            <Item label="操作时间"><Input value={this.state.viewData.operation_time } /></Item>
            <Item label="入库人"><Input value={this.state.viewData.worker } /></Item>
            <Item label="入库时间"><Input value={this.state.viewData.in_time } /></Item>
            <Item label="入库数量"><Input value={this.state.viewData.in_number } /></Item>
            <Item label="存放位置"><Input value={this.state.viewData.store_place } /></Item>
            <Item label="备注说明"><Input value={this.state.viewData.remark } /></Item>
          </span>
          <span style={{flex:'1', display: 'none'}}>
            <Item label="培养周期"><Input value={this.state.viewData } /></Item>
            <Item label="分离人"><Input value={this.state.viewData } /></Item>
            <Item label="分离时间"><Input value={this.state.viewData } /></Item>
            <Item label="需氧类型"><Input value={this.state.viewData } /></Item>
            <Item label="菌落描述"><Input value={this.state.viewData } /></Item>
            <Item label="正面颜色"><Input value={this.state.viewData } /></Item>
            <Item label="反面颜色"><Input value={this.state.viewData } /></Item>
            <Item label="孢子有无"><Input value={this.state.viewData } /></Item>
            <Item label="是否产色素"><Input value={this.state.viewData } /></Item>
            <Item label="备注"><Input value={this.state.viewData } /></Item>
            <Item wrapperCol={{ span: 12, offset: 4 }}>
              <Row guuter={16}>
                <Col span={6}>
                  <Button type="primary" htmlType="submit">
                    确定
                  </Button>
                </Col>
              </Row>
            </Item>
          </span>
        </div>
      </Form>
        </Modal>
       
        <Table
          rowSelection={rowSelection}
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          scroll={{ x: 3000}}
        />
        <div style={{marginLeft: 16}}>
          <Button onClick={this.handleAdd} type="primary" >
            添加
          </Button>
          <Button disabled={this.state.newData.id == null} onClick={(record) => this.handleSave(record, true)}  type="primary" style={{ marginLeft: 16 }}>
            保存
          </Button>
        </div>
      </Content>
    );
  }
}

const ScreeningSaveInfo = Form.create()(EditableTable);
export default ScreeningSaveInfo;